﻿using System.Collections.Generic;
using System.Net.Sockets;

namespace VirtualKeyboard.Service.TcpServices
{
    internal class BufferManager
    {
        private readonly int itemBufferLength;
        private readonly int itemCount;
        private readonly byte[] buffer;
        private readonly Stack<int> offsetStack;
        private readonly object lockObj = new object();

        private int currentIndex = 0;

        public BufferManager(int itemBufferLength, int itemCount)
        {
            this.itemBufferLength = itemBufferLength;
            this.itemCount = itemCount;
            this.buffer = new byte[itemBufferLength * itemCount];
            this.offsetStack = new Stack<int>(itemCount);
        }

        public bool SetBuffer(SocketAsyncEventArgs e)
        {
            lock (lockObj)
            {
                if (offsetStack.Count > 0)
                {
                    int index = offsetStack.Pop();
                    e.SetBuffer(buffer, index, itemBufferLength);
                }
                else
                {
                    if (currentIndex > itemCount * itemBufferLength)
                    {
                        return false;
                    }
                    e.SetBuffer(buffer, currentIndex, itemBufferLength);
                    currentIndex += itemBufferLength;
                }
                return true;
            }
        }

        public void FreeBuffer(SocketAsyncEventArgs e)
        {
            lock (lockObj)
            {
                offsetStack.Push(e.Offset);
                e.SetBuffer(null, 0, 0);
            }
        }
    }
}
